package com.hmall.search.service.impl;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.CompletionSuggestOption;
import co.elastic.clients.elasticsearch.core.search.Suggestion;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.search.domain.po.Item;
import com.hmall.search.domain.po.ItemDoc;
import com.hmall.search.mapper.SearchMapper;
import com.hmall.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @Author mr.zhao
 * @Date 2025/6/26 20:37
 */
@Service
public class SearchServiceImpl extends ServiceImpl<SearchMapper, Item> implements SearchService {

	@Autowired
	private ElasticsearchClient esClient;

	/**
	 * 自动补全
	 *
	 * @param key
	 * @return
	 */
	@Override
	public List<String> autoSuggestion(String key) {
		List<String> result = new ArrayList<>();
		try {
			//执行查询商品请求
			SearchResponse<ItemDoc> response = esClient.search(s->
							s.index("items")
									.trackTotalHits(t->t.enabled(true)) //设置确定查询真实总记录数,否则最多数量上限10000
									.suggest(
											ss->ss.suggesters("my_suggest",
													fs->fs.text(key).completion(
															c->c.field("suggestion") //搜索的字段名
																	.size(100) //搜索的条数
																	.skipDuplicates(true) //跳过重复词(去重)
													)
											)
									)
					, ItemDoc.class);

			//处理响应结果
			List<Suggestion<ItemDoc>> suggestionList = response.suggest().get("my_suggest");
			Suggestion<ItemDoc> suggestion = suggestionList.get(0);
			List<CompletionSuggestOption<ItemDoc>> options = suggestion.completion().options();

			options.forEach(x->{
				String text = x.text();
				result.add(text);
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}
